package com.demo.parallelstream;

import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.LongStream;

public class TestCorrectParallel {
    public static class Accumulator {
        public AtomicLong total = new AtomicLong(0);
        public void add(long value) {
            total.addAndGet(value);
        }
    }

    public static long sideEffectSum(long n) {
        Accumulator accumulator = new Accumulator();
        LongStream.rangeClosed(1, n).forEach(accumulator::add);
        return accumulator.total.get();
    }

    public static long sideEffectParallelSum(long n) {
        Accumulator accumulator = new Accumulator();
        LongStream.rangeClosed(1, n).parallel().forEach(accumulator::add);
        return accumulator.total.get();
    }

    public static void main(String[] args) {
        System.out.println("SideEffect sum done in: " +
                TestPerformance.measureSunPerf(TestCorrectParallel::sideEffectSum, 10_000_000) + "msecs");

        System.out.println("SideEffectParallel sum done in: " +
                TestPerformance.measureSunPerf(TestCorrectParallel::sideEffectParallelSum, 10_000_000) + "msecs");
    }
}
